<template>
	<div class="pagination">
		<button
			class="prev"
			@click="cutPage(currentPage - 1)"
			:disabled="currentPage <= 1"
		>
			上一页
		</button>
		<ul class="pager">
			<li
				:class="{
					active: currentPage === 1,
				}"
				@click="cutPage(1)"
			>
				1
			</li>
			<li v-show="startEnd.start > 2">
				<i>....</i>
			</li>
			<li
				v-for="(item, index) in startEnd.end - startEnd.start + 1"
				:key="item"
				:class="{
					active: currentPage === startEnd.start + index,
				}"
				@click="cutPage(startEnd.start + index)"
			>
				{{ startEnd.start + index }}
			</li>
			<li v-show="startEnd.end < totalPages - 1">
				<i>....</i>
			</li>
			<li
				v-if="totalPages > 1"
				:class="{
					active: currentPage === totalPages,
				}"
				@click="cutPage(totalPages)"
			>
				{{ totalPages }}
			</li>
		</ul>
		<button
			class="next"
			:disabled="currentPage >= totalPages"
			@click="cutPage(currentPage + 1)"
		>
			下一页
		</button>
	</div>
</template>

<script>
export default {
	name: "PaginAtion",
	props: ["currentPage", "pageSize", "total"],
	data() {
		return {
			// totalPages: "",
		};
	},
	methods: {
		cutPage(currentPage) {
			this.$emit("goPage", currentPage);
			// this.$emit("size-change");
			// this.$emit("current-change");
			// console.log(totalPages);
		},
	},
	computed: {
		//总页数
		totalPages() {
			// console.log(Math.ceil(this.total / this.pageSize));
			return Math.ceil(this.total / this.pageSize);
		},

		// 中间健
		startEnd() {
			const max = this.totalPages - 1;

			if (this.totalPages <= 2) {
				// 说明不需要展示中间按钮
				return {
					start: 2,
					end: 1,
				};
			}

			// 总页数小于7，不用计算start和end
			// start一定是2
			// end一定是总页数-1
			if (this.totalPages <= 7) {
				return {
					start: 2,
					end: max,
				};
			}

			let start = this.currentPage - 2;
			// start有最小值
			if (start < 2) start = 2;

			let end = start + 4;
			// end有最大值
			if (end > max) {
				end = max;
				start = end - 4;
			}

			return {
				start,
				end,
			};
		},
	},
};
</script>

<style lang="less" scoped>
.pagination {
	display: flex;
	justify-content: center;
	align-items: center;
	font-size: 14px;
	color: #303133;
	.prev,
	.next {
		cursor: pointer;
		border: none;
		padding: 0 15px;
		display: flex;
		justify-content: center;
		align-items: center;
		height: 32px;
		width: 72px;
		background-color: #fff;
		&:hover {
			color: #409eff;
			background-color: #f1f2f3;
		}
		&:disabled {
			color: #a8abb2;
			opacity: 0.5;
			cursor: not-allowed;
		}
	}
	.pager {
		display: flex;
		align-items: center;
		li {
			width: 18px;
			height: 18px;
			border: 1px solid #f1f2f3;
			border-radius: 5px;
			padding: 8px;
			margin-right: 8px;
			display: flex;
			justify-content: center;
			align-items: center;
			cursor: pointer;
			&:hover {
				color: #409eff;
				background-color: #f1f2f3;
			}
			&.active {
				background-color: #00aeec;
			}
		}
	}
}
.prev {
	margin-right: 8px;
}
</style>
